package com.AnywheeBt;

import java.io.File;

import com.AnywheeBt.PbapClient.utils.BTConfig;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import java.util.Set;
import android.widget.Toast;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadsetClient;
import android.bluetooth.BluetoothHeadsetClientCall;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothA2dpSink;
import android.os.SystemProperties;
import android.os.PowerManager;


public class BtReceiver extends BroadcastReceiver{
	protected static final String TAG = "BtReceiver";
	private static boolean mBoot = false;
	//zqg 0303 start add send to AIOS ACTION
	public static final String AIOS_INCOMING_RINGING = "action.bt.AIOS_INCOMING_RINGING";//来电响铃
	public static final String AIOS_INCOMING_OFFHOOK = "action.bt.AIOS_INCOMING_OFFHOOK";/*来电通话中*/
	public static final String AIOS_INCOMING_IDLE = "action.bt.AIOS_INCOMING_IDLE";//来电空闲状态
	public static final String AIOS_OUTGOING_RINGING = "action.bt.AIOS_OUTGOING_RINGING";//打电话出去等待对方接听
	public static final String AIOS_OUTGOING_OFFHOOK = "action.bt.AIOS_OUTGOING_OFFHOOK";//打电话出去通话中
	public static final String AIOS_OUTGOING_IDLE = "action.bt.AIOS_OUTGOING_IDLE";//打电话空闲状态
	private static boolean isIncomingCall;//判断是否是来电
	public static int IncomingCallOneshot = 0;//只执行一次发广播操作
	private DatabaseHelper mDatabaseHelper;
    private PowerManager pm = null;
    private PowerManager.WakeLock wl = null;
	//zqg 0303 end add
	private boolean isMyServiceRunning(Context context,String ServiceName) {
	    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
	    for(RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
	        if (ServiceName.equals(service.service.getClassName())) {	        	
	        	return true;
	        }
	    }
	    return false;
	}
	/**
	 * 发送广播给AIOS，通知蓝牙的通话状态
	 * @param context　上下文
	 * @param action　　电话状态
	 */
	public void sendBroadcastToAIOS(Context context,String action){
		Intent intent=new Intent(action);
		context.sendBroadcast(intent);
		//Log.i(TAG,"****sendBroadcastToAIOS action===:"+action);
	}
	@Override
	public void onReceive(Context context, Intent intent) {	
		String action = intent.getAction();  
		mDatabaseHelper=DatabaseHelper.getDatabaseHelper(context);
		if(BTService.btServiceRuning == false){
			Log.i(TAG,"btService no Runing,start it");
			Intent msgIntent = new Intent(context,BTService.class);
			context.startService(msgIntent);
		}
		
		if( action.equals(Intent.ACTION_BOOT_COMPLETED) ) {						
//			Log.i(TAG,"BT boot Service start");
//		    Intent msgIntent = new Intent(context,BTService.class);
//		    context.startService(msgIntent);	
		}else if(action.equals(Intent.ACTION_MEDIA_MOUNTED) ) {
			if(intent.getDataString().equalsIgnoreCase("file:///mnt/sdcard")) {
				if( false == mBoot ) {
	    			mBoot = true;
	    			SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(context);			
	    			boolean bBtOpen=prefs.getBoolean("bt_open", true);			
	    			if( bBtOpen && false==isMyServiceRunning(context,"com.AnywheeBt.BTService")) {  
	    				Log.i(TAG,"BT boot Service start");
	    		        Intent msgIntent = new Intent(context,BTService.class);
	    		        context.startService(msgIntent);	
	    		    } 
				}	
			}	
		}
		//蓝牙连接状态
		else if(action.equals(BluetoothHeadsetClient.ACTION_CONNECTION_STATE_CHANGED)){
			int newState = (int)intent.getExtras().get(BluetoothProfile.EXTRA_STATE);
			BluetoothDevice dev = (BluetoothDevice)intent.getExtras().get(BluetoothDevice.EXTRA_DEVICE);
			//int preState = intent.getExtras().get(BluetoothProfile.EXTRA_PREVIOUS_STATE);
			//Log.i(TAG,"****ACTION_CONNECTION_STATE_CHANGED stat:" + newState);
			if(newState == 2){
				SzhBAction.SetBtState(true,dev);
				SystemProperties.set("persist.btcar.condevaddr", dev.getAddress());
				Intent intentBtconnect = new Intent();
				intentBtconnect.setAction(BTConfig.BT_CONNECTED);
				context.sendBroadcast(intentBtconnect);
				Log.d("zcl","----BT_CONNECTED-----");
				BTApp.getAppConext(context).setProperty("bt_conn_statu","true");
			}
			else{
				SzhBAction.SetBtState(false,null);
				Intent intentBtdisconnect = new Intent();
				intentBtdisconnect.setAction(BTConfig.BT_DISCONNECTED);
				context.sendBroadcast(intentBtdisconnect);
				Log.d("zcl","----BT_DISCONNECTED-----");
				BTApp.getAppConext(context).setProperty("bt_conn_statu","false");
			}

			SzhBAction.setBtHfpclientState(newState,dev);

			if(dev != null){
				Log.i(TAG,"****ACTION_CONNECTION_STATE_CHANGED dev.getName():"+dev.getName());
				SzhBAction.SetBtName(dev.getName());
			}
		}else if(action.equals(BluetoothHeadsetClient.ACTION_CALL_CHANGED)){
			BluetoothHeadsetClientCall c = (BluetoothHeadsetClientCall)intent.getExtras().get(BluetoothHeadsetClient.EXTRA_CALL);
			//zqg 0303 add
			//打电话出去状态变化：CALL_STATE_DIALING－＞CALL_STATE_ALERTING－＞CALL_STATE_ACTIVE－＞CALL_STATE_TERMINATED
			//接电话状态变化：CALL_STATE_INCOMING－＞CALL_STATE_ACTIVE－＞CALL_STATE_TERMINATED
			String num = c.getNumber();
			//Log.e(TAG, "Bluetooth ACTION_CALL_CHANGED c.getState()==="+c.getState());
			Intent tempIntent = new Intent();
			tempIntent.setAction("com.rk.bt.callStatchange"); 
			//Log.i(TAG,"******************ACTION_CALL_CHANGED num:"+num);
			//zqg 0303 outgoing call state
			if(c.getState() == BluetoothHeadsetClientCall.CALL_STATE_INCOMING){
    			//来电状态
                Log.d("zcl","incoming call ----");
				isIncomingCall=true;
                if(pm == null){
                    pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
                }
                if(!pm.isScreenOn()){
                    Log.d("zcl","the screen is off");
                    //获取PowerManager.WakeLock对象，后面的参数|表示同时传入两个值，最后的是调试用的Tag
                    wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
                    //点亮屏幕
                    wl.acquire();
                    wl.release();
                }
                  if(BtCallBack.oneshot == 0){
					BtCallBack.oneshot = 1;
					//自动接听
					if(BTApp.getAppConext(context).isMbAutoAnswer()){
						//自动接听
						SzhBAction.acceptCall();
						Log.e("Yanglin", "SzhBAction.acceptCall()");
					}else{
						Log.e("Yanglin", "AutoAnswer false");
						//此处不应该直接跳到蓝牙接听界面,而是应该发送来电广播给Aios,确定接听后才会跳转到通话界面
//						Intent acintent = new Intent();
//						acintent.setClass(context, BtCallBack.class);
//						acintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						acintent.putExtra("strNumber", num);
//						acintent.putExtra("isDialout", false);
//						context.startActivity(acintent);
						//当来电的时候，发送来电广播给aios,aios接收到再判断接听或者拒绝
						//此处应该传来电姓名和来电号码给aios,但是只有号码，后续继续完善
						//只执行一次发广播操作
						Intent aiosIntent=new Intent("action.bt.AIOS_INCOMING_RINGING");
						aiosIntent.putExtra("number", num);
						if(mDatabaseHelper.getNameByNum(num)!=null){
							aiosIntent.putExtra("name",mDatabaseHelper.getNameByNum(num));
						}
						context.sendBroadcast(aiosIntent);
						//Log.i(TAG,"******************send incomint ringing to aios num==:"+num+",,,name=="+mDatabaseHelper.getNameByNum(num));
						tempIntent.putExtra("callStat", BluetoothHeadsetClientCall.CALL_STATE_INCOMING);
						context.sendBroadcast(tempIntent);
					}
				}	
    		}else if(c.getState() == BluetoothHeadsetClientCall.CALL_STATE_DIALING){
    			//呼出电话
    			Log.i(TAG, "c.isOutgoing()===="+c.isOutgoing()+",,,isOutgoingCall=true");
				if(c.isOutgoing()){
					//if(BtCallBack.oneshot == 0){
						//BtCallBack.oneshot = 1;
						Intent acintent = new Intent();
						acintent.setClass(context, BtCallBack.class);
						acintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						acintent.putExtra("strNumber", num);
						acintent.putExtra("isDialout", true);
						context.startActivity(acintent);
					//}
				}
				tempIntent.putExtra("callStat", BluetoothHeadsetClientCall.CALL_STATE_DIALING);
				context.sendBroadcast(tempIntent);
				sendBroadcastToAIOS(context,AIOS_OUTGOING_RINGING);
    		}else if(c.getState() == BluetoothHeadsetClientCall.CALL_STATE_ACTIVE){ 
    			//通话中，需要分别是来电通话中，还是去电通话中		
				tempIntent.putExtra("callStat", BluetoothHeadsetClientCall.CALL_STATE_ACTIVE);
				context.sendBroadcast(tempIntent);
				//Log.i(TAG, "BtCallBack.bBtCallPhone===="+BtCallBack.bBtCallPhone+",,isIncomingCall=="+isIncomingCall);
				//去电通话中
				if(BtCallBack.bBtCallPhone){
					sendBroadcastToAIOS(context,AIOS_OUTGOING_OFFHOOK);
				}
				//来电通话中
				if(isIncomingCall){
					if(IncomingCallOneshot == 0){
						IncomingCallOneshot = 1;
						sendBroadcastToAIOS(context,AIOS_INCOMING_OFFHOOK);
					}
				}
    		}else if(c.getState() == BluetoothHeadsetClientCall.CALL_STATE_TERMINATED){
				//挂断电话，需要分别是来电结束通话，还是去电结束通话
    			tempIntent.putExtra("callStat", BluetoothHeadsetClientCall.CALL_STATE_TERMINATED);
				context.sendBroadcast(tempIntent);
                BtCallBack.oneshot = 0;                
                //去电结束通话
				if(BtCallBack.bBtCallPhone){
					sendBroadcastToAIOS(context,AIOS_OUTGOING_IDLE);
					BtCallBack.bBtCallPhone=false;
				}
				//来电结束通话
				if(isIncomingCall){
                  Log.d("zcl","call down-----");
					sendBroadcastToAIOS(context,AIOS_INCOMING_IDLE);
					isIncomingCall=false;
				}
    		}  else if(c.getState() == BluetoothHeadsetClientCall.CALL_STATE_ALERTING ){ 
				if(c.isOutgoing()){
					if(BtCallBack.oneshot == 0){
						BtCallBack.oneshot = 1;
						Intent acintent = new Intent();
						acintent.setClass(context, BtCallBack.class);
						acintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						acintent.putExtra("strNumber", num);
						acintent.putExtra("isDialout", true);
						context.startActivity(acintent);
					}

				}
				tempIntent.putExtra("callStat", BluetoothHeadsetClientCall.CALL_STATE_DIALING);
				context.sendBroadcast(tempIntent);
    		} 
		}else if(action.equals("android.bluetooth.a2dp.sink.profile.action.PLAYING_STATE_CHANGED")){
				if(intent.getExtras().get(BluetoothProfile.EXTRA_STATE) != null)
					BtMusic.playStat = (int)intent.getExtras().get(BluetoothProfile.EXTRA_STATE);
								
				Log.i(TAG,"***********PLAYING_STATE_CHANGED playStat:"+BtMusic.playStat);
		}else if(action.equals(BluetoothHeadsetClient.ACTION_AG_EVENT)){
				
				if(intent.getExtras().get(BluetoothHeadsetClient.EXTRA_NETWORK_STATUS) != null){
					int network = (int)intent.getExtras().get(BluetoothHeadsetClient.EXTRA_NETWORK_STATUS);

					Log.i(TAG,"***********ACTION_AG_EVENT network:"+network);
					if(network == 1)
						SzhBAction.SetNetWorkService(true);
					else
						SzhBAction.SetNetWorkService(false);
				}
		}else if(action.equals("android.bluetooth.a2dp.sink.profile.action.CONNECTION_STATE_CHANGED")){
			int newState = (int)intent.getExtras().get(BluetoothProfile.EXTRA_STATE);
			BluetoothDevice dev = (BluetoothDevice)intent.getExtras().get(BluetoothDevice.EXTRA_DEVICE);
			//int preState = intent.getExtras().get(BluetoothProfile.EXTRA_PREVIOUS_STATE);
			Log.i(TAG,"****a2dp.sink stat:"+newState);
			if(newState == 2)
				SzhBAction.SetBtA2dpSinkState(true,dev);
			else
				SzhBAction.SetBtA2dpSinkState(false,null);
		}else if(action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)){
			int  stat = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,0);
			Log.i(TAG," btstat:"+stat);
			if(stat == BluetoothAdapter.STATE_ON && BTApp.getAppConext(context).isMbAutoConnect()){
				String lastConDevAddr = SystemProperties.get("persist.btcar.condevaddr", "null");
				Log.i(TAG," btstat:lastConDevAddr:"+lastConDevAddr);
				if(lastConDevAddr.equals("null"))
					return;
				BluetoothAdapter	mAdapter= BluetoothAdapter.getDefaultAdapter();
				Set<BluetoothDevice> bondedDevices = mAdapter.getBondedDevices();
				for (BluetoothDevice device : bondedDevices){
					if(lastConDevAddr.equals(device.getAddress())){
						Log.i(TAG," btstat:device:"+device.getAddress());
						SzhBAction.ConnectHfpclientDevice(device);
						SzhBAction.ConnectA2dpSinkDevice(device);
						return;
					}
				}
			}
		}
		else if(action.equals(BluetoothHeadsetClient.ACTION_AUDIO_STATE_CHANGED)){
			BTService.btAudioStat = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,0);
			Log.i(TAG,"****btAudioStat:"+BTService.btAudioStat);
		}else if(action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)){
			/*BluetoothDevice device =
	              intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
	                BluetoothDevice.ERROR);
	        if (type == BluetoothDevice.PAIRING_VARIANT_PIN) {
	            String pinCode = SystemProperties.get("persist.service.bdroid.pincode", "0000");
	            Log.e(TAG, "PAIRING_VARIANT_PIN, pinCode[" + pinCode + "]");
	            byte[] pinBytes = BluetoothDevice.convertPinToBytes(pinCode);
	            if (pinBytes != null) {
	                device.setPin(pinBytes);
	            }                
	        }*/
		}
		//接收到翼卡发来的信息
		else if (action.equals(BTConfig.ECAR_SEND_ACTION)) {
		}
		//语音发过来的BT操作命令
		else if(action.equals(BTConfig.BT_OPEN_ACTION))
		{
			Log.e("=======Yanglin=======", "BtReceiver  action = " + BTConfig.BT_OPEN_ACTION);
			OpenCloseBt(true);
		}
		else if(action.equals(BTConfig.BT_CLOSE_ACTION))
		{
			Log.e("=======Yanglin=======", "BtReceiver  action = " + BTConfig.BT_OPEN_ACTION);
			OpenCloseBt(false);
		}
		else if(action.equals(BTConfig.BT_GET_CONTACTS))
		{
		}
		else if(action.equals(BTConfig.BT_UPDATE_CONTACTS))
			
		{
		}
		else if(action.equals(BTConfig.BT_UPDATE_CONTACTS_FINISHED))
		{
		}
		else if(action.equals(BTConfig.BT_DISCONNECTED))
			
		{
		}
		else if(action.equals(BTConfig.BT_HANG_UP))
			
		{
		}
//		}else if(action.equals("android.bluetooth.a2dp.sink.profile.action.PLAYING_STATE_CHANGED")){
//				if(intent.getExtras().get(BluetoothProfile.EXTRA_STATE) != null)
//					BtMusic.playStat = (int)intent.getExtras().get(BluetoothProfile.EXTRA_STATE);
//
//				Log.i(TAG,"***********PLAYING_STATE_CHANGED playStat:"+BtMusic.playStat);
//		}
		else if(action.equals("action.intent.AIOS_DIAL")){//接收到aios打电话的通知，调用蓝牙API打电话....需要发接通中的消息出去
//			if(BtService.mBtStatus != BTManager.STATE_CONNECTED){
//				openBt();
//				Toast.makeText(context, R.string.msg_unconnectedorcalling, 1000).show();
//				return;
//			}
			String phoneNumber = intent.getStringExtra("number");
			//Log.e(TAG,"shou dao AIOS_DIAL number====="+phoneNumber);
			SzhBAction.CallPhone(phoneNumber);
		}else if (action.equals("action.intent.AIOS_ACCEPT")) {//接收到aios接听的广播，直接打电话
			isIncomingCall=true;
			String Number = intent.getStringExtra("number");
            Intent acintent = new Intent();
            acintent.setClass(context, BtCallBack.class);
            acintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            acintent.putExtra("strNumber", Number);
            acintent.putExtra("isDialout", false);
            context.startActivity(acintent);
            SzhBAction.acceptCall();
			//Log.e(TAG,"shou dao AIOS_ACCEPT number====="+Number);
		}else if (action.equals("action.intent.AIOS_REJECT")) {//接收到aios拒接的广播，直接挂断电话
			SzhBAction.hangupCall();
			//Log.e(TAG,"shou dao AIOS_REJECT number=====");
		}else if(action.equals("ACTION_CHOICE_NAV_APPLICATION")) {
            String key = intent.getStringExtra("car_nav_choice");
            if(key.equals("ecard")) {
                BTApp.getAppConext(context).setProperty("ddh","false");
            }else{
                BTApp.getAppConext(context).setProperty("ddh","true");
            }
		}else if(action.equals("com.aios.adapter.callrecord.open")){
			Intent mIntent = new Intent(context, BtCallList.class);
			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
			context.startActivity(mIntent);
		}else if(action.equals("com.aios.adapter.callrecord.close")){
			Intent i = new Intent();
			i.setAction("com.anywheetbt.btcalllist.close");
			context.sendBroadcast(i);
		}
	}
	
	//打开蓝牙
   private void OpenCloseBt(boolean bOpen) {
    	BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
		//
		if(!bOpen) {
			adapter.disable();				
		} else {
			adapter.enable();
	        adapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
		}					
    }
	
	
	public void onEcarReceiver(Intent intent, int cmd) {
		if ((BTConfig.HAND_UP_CMD & cmd) == 1) {
			// Hangup
		}
		if ((BTConfig.MAKE_CALL_CMD & cmd) == 2) {
			// call

		}

		if ((BTConfig.SEND_NAVI_CMD & cmd) == 4) {
			//
		}

		if ((BTConfig.SPEAKER_DISABLE_CMD & cmd) == 8) {
			// disable spk
		}

		if ((BTConfig.SPEAKER_ENABLE_CMD & cmd) == 16) {
			// enable spk
		}
	}
	
	//
	private static final int MSG_CLOSESPK = 0;
	private static final int MSG_OPENSPK = 1;
	private static final int MSG_OPENBT = 2;
	private static final int MSG_CLOSEBT = 3;
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case MSG_CLOSESPK:
				break;
			case MSG_OPENSPK:
				break;
			case MSG_OPENBT:
				break;
			case MSG_CLOSEBT:
				break;
			default:
				break;
			}
		}
	};
}
